package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.multi_image_selector.MultiImageSelectorActivity;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.toast.LoadToast;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.Log;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.util.NetUtil;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import logic.constants.DefaultConsts;
import logic.util.ImageLoaderUtil;
import logic.util.Util;
import logic.util.Utils;


/**
 * @author xuzhijun
 * @date 2015年5月6日下午3:07:10
 */
public class NewInteractionCenterUserPublishActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
	private static final int      REQUEST_IMAGE      = 2;
	private final int             PIC_MAX_LENGTH     = 6;
	
	private Context               mContext;
	//Title
	private TextView              tvTitle;
	private Button                btnBack;
	private Button                btnSubmit;
	
	//
	private ImageView             addFriend;
	private EditText              edtContent;
	private LinearLayout          friendLL;
	private ArrayList<String>     mSelectPath;
//	private LoadingDialog         loadingDialog;
	
	private List<FriendImageView> listFriend         = new ArrayList<FriendImageView>();
	private ArrayList<String>     selectedPictureAll = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_interaction_center_user_publish);
		mContext = this;
		initView();
		initData();
		initListener();
	}
	
	private Handler handler = new Handler()
	                        {
		                        @Override
		                        public void handleMessage(Message msg) {
			                        
		                        }
	                        };
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	private void initView() {
		//Title		
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setVisibility(View.GONE);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		btnSubmit = (Button) findViewById(R.id.common_header_publish);
		btnSubmit.setVisibility(View.VISIBLE);
		//		btnSubmit.setText("发布");
		
		addFriend = (ImageView) findViewById(R.id.new_interation_center_user_publish_add_friend_img);
		edtContent = (EditText) findViewById(R.id.new_interation_center_user_publish_cotent_tv);
		Util.showInputMethodManager(mContext);
		friendLL = (LinearLayout) findViewById(R.id.new_interation_center_user_publish_at_friend_ll);
	}
	
	private void initData() {
//		loadingDialog = new LoadingDialog(mContext);
		
	}
	
	private void initListener() {
		btnBack.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		addFriend.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		Util.hideInputMethodManager(mContext, edtContent);
		switch (v.getId()) {
			case R.id.common_header_back:
				finish();
				break;
			case R.id.common_header_publish:
				//				Utils.ToastShow(mContext, "发送");
				submit();
				break;
			case R.id.new_interation_center_user_publish_add_friend_img:
				Intent intent = new Intent(this, MultiImageSelectorActivity.class);
				// 是否显示拍摄图片
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
				// 最大可选择图片数量
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, PIC_MAX_LENGTH);
				// 选择模式
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
				// 默认选择
				if (selectedPictureAll != null && selectedPictureAll.size() > 0)
				{
					intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
				}
				startActivityForResult(intent, REQUEST_IMAGE);
				break;
		}
	}
	
	private void submit() {
		String[] picPATHs = selectedPictureAll.toArray(new String[selectedPictureAll.size()]);
		if (!NetUtil.isNetworkConnected(mContext))
		{
			new NoNetDialog(mContext).show();
		}
		else
		{
			
			try
			{
				
				if (picPATHs.length > 6)
				{
					Utils.ToastShow(mContext, "最多上传6张图片哦~");
				}
				else if (Utils.isEmpty(edtContent.getText().toString().trim()))
				{
					Utils.ToastShow(mContext, R.string.new_i_publish_content_empty);
				}
				else
				{
					if (edtContent.getText().toString().trim().length() > 140)
					{
						Utils.ToastShow(mContext, "不能超过140个字");
					}
					else
					{
//						loadingDialog.show();
						showToast();
						btnSubmit.setEnabled(false);
						ActionHelp.addTopic(mContext, edtContent.getText().toString().trim(), new TextHttpResponseHandler()
						{
							
							@Override
							public void onSuccess(int statusCode, Header[] headers, String responseString) {
//								loadingDialog.dismiss();
								success();
							}
							
							@Override
							public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//								loadingDialog.dismiss();
								closeToast(-1);
								btnSubmit.setEnabled(true);
								Log.i("errorCode:" + statusCode + " responseString:" + responseString);
								if (statusCode > 999)
								{
									JSONObject jsonObject;
									try
									{
										jsonObject = new JSONObject(responseString);
										String resultString = jsonObject.getString("returnObject");
										Utils.ToastShow(mContext, resultString);
									}
									catch (JSONException e)
									{
										Utils.ToastShow(mContext, "数据发布异常");
										e.printStackTrace();
									}
									
								}
							}
						}, picPATHs);
					}
					
				}
			}
			catch (FileNotFoundException e)
			{
				Utils.ToastShow(mContext, "发布失败");
				e.printStackTrace();
			}
		}
	}
	private void success(){
		closeToast(1);
		btnSubmit.setEnabled(true);
		Utils.ToastShow(mContext, "发布成功");
		new Handler().postDelayed(new Runnable()
		{
			@Override
			public void run() {
				setResult(RESULT_OK);
				finish();
			}
		}, 800);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_IMAGE)
		{
			if (resultCode == RESULT_OK)
			{
				mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
				mSelectPath.removeAll(selectedPictureAll);
				selectedPictureAll.addAll(mSelectPath);
				for (String p : mSelectPath)
				{
					FriendImageView friendImageView = new FriendImageView(p);
					friendLL.addView(friendImageView.getFriendView(), friendLL.getChildCount() - 1);
					listFriend.add(friendImageView);
				}
				notyPicChange();
				
			}
		}
		
	}
	
	
	private void notyPicChange() {
		if (selectedPictureAll.size() > 5)
		{
			addFriend.setVisibility(View.GONE);
		}
		else
		{
			addFriend.setVisibility(View.VISIBLE);
		}
		
	}
	
	private class FriendImageView
	        implements
	        OnClickListener
	{
		private View     friendView;
		public ImageView friendImg;
		public ImageView deleteImg;
		
		public String    imagePath = "";
		
		public FriendImageView(String imagePath) {
			friendView = LayoutInflater.from(mContext).inflate(R.layout.new_interaction_center_user_publish_friend_item_img, friendLL, false);
			friendImg = (ImageView) friendView.findViewById(R.id.new_interation_center_user_publish_friend_item_img);
			friendImg.setOnClickListener(this);
			deleteImg = (ImageView) friendView.findViewById(R.id.new_interation_center_user_publish_friend_item_delete);
			deleteImg.setOnClickListener(this);
			this.imagePath = imagePath;
			ImageLoaderUtil.loadLocalUrl(imagePath, friendImg);
		}
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.new_interation_center_user_publish_friend_item_delete:
					remove();
					break;
				case R.id.new_interation_center_user_publish_friend_item_img:
					Intent atlasSeeIntent = new Intent(NewInteractionCenterUserPublishActivity.this, NewInteractionAtlasSeeActivity.class);
					atlasSeeIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.NI_FROM_LOCALURL);
					atlasSeeIntent.putExtra(DefaultConsts.NI_ATLASSEE_URL, selectedPictureAll);
					atlasSeeIntent.putExtra(DefaultConsts.NI_POSITION, listFriend.indexOf(this));
					NewInteractionCenterUserPublishActivity.this.startActivity(atlasSeeIntent);
					break;
			}
			
		}
		
		public void remove() {
			listFriend.remove(this);
			selectedPictureAll.remove(imagePath);
			friendLL.removeView(friendView);
			notyPicChange();
		}
		
		public View getFriendView() {
			return this.friendView;
		}
		
	}
	@Override
	protected void onPause() {
	    super.onPause();
	    closeToast(0);
	}
	
	
	private LoadToast toast;
    private final String loadingLable = "正在发布...";
    /** LoadToast是否显示中 */
    public boolean isToastShowing(){
    	return null!=toast && toast.isShowing();
    }
    /** 显示LoadToast */
    public void showToast(){
    	if(null == toast){
    		toast = new LoadToast(this);
    		toast.setText(loadingLable);
    		toast.setTranslationY(200).setBackgroundColor(Color.parseColor("#FFFFFF")).setProgressColor(Color.BLUE);
    	}
    	if(!isToastShowing()) toast.show();
    }
    /**
     * 关闭LoadToast
     * @param type 0:关闭，1：成功，-1：错误
     */
    public void closeToast(int type){
    	if(null == toast) return;
    	switch(type){
    		case -1:
    			toast.error();
    			break;
    		case 0:
    			toast.close();
        		toast = null;
    			break;
    		case 1:
    			toast.success();
    			break;
    	}
    }
}
